using UnityEngine;
using MySql.Data.MySqlClient;
using System;
using System.Net;

public class LoginScreen: MonoBehaviour
{
    string username;
    string password;
    string message;
	public GUITexture Labels;
	public GUIStyle textBox;
	public GUIStyle messageStyle; 
	public GUIStyle blankStyle;
	public Texture logo;
		
    void Start()
    {
        username = "";
        password = "";
        message = "";
		Labels.pixelInset = new Rect(-150, -220, 300, 343);
		textBox.normal.textColor = Color.white;
    }

    void OnGUI()
    {
		GUI.Button(new Rect(0, 50, 160, 45), logo, blankStyle);

		int width = Screen.width / 2;
		int height = Screen.height / 2;
		GUI.SetNextControlName("username");
		username = GUI.TextField(new Rect(width - 110, height - 21, 220, 40), username, 256, textBox);
		GUI.SetNextControlName("password");
		password = GUI.PasswordField(new Rect(width - 110, height + 47, 220, 40), password, "*"[0], 256, textBox);
		
		GUI.enabled = false;
		message = GUI.TextField(new Rect(width - 110, height + 85, 220, 40), message, 256, messageStyle);
		GUI.enabled = true;

		if (GUI.GetNameOfFocusedControl() == string.Empty)
		{
			GUI.FocusControl("username");
		}
		
		username = username.Replace("\n", "");
		password = password.Replace("\n", "");	// Working on mac & windows; System.Environment.NewLine does not work on windows.
		
		if (username.Length > 10)
		{
			username = username.Substring(0, 10);
		}

		if (password.Length > 10)
		{
			password = password.Substring(0, 10);
		}

		GUI.SetNextControlName ("login");
		
		GUI.skin.button.fontSize = 16;
		GUI.skin.button.fontStyle = UnityEngine.FontStyle.Bold;
			
		if (GUI.Button(new Rect(width - 50, height + 120, 100, 50), "Login") || (Event.current.keyCode == KeyCode.Return))
        {
            // Use Debug.isDebugBuild instead for debugging Debug Builds.
			#if UNITY_EDITOR
            if (username == "" && password == "")
            {
				username = "demo";
				password = "d3m0";	// XXX: passwords should be encrypted.
            }
			#endif
			
			if (username == "" || password == "")
			{
				message = "Provide username and password";
				return;
			}
			
			message = "Please wait...";
			
			try
	        {
	            MySqlConnection connection = new MySqlConnection(Configuration.MySQLConnectionString);
	            connection.Open();
				
				using (connection)
				{
					string query = "SELECT u.user_id, u.name AS user_name, g.CaseSet_case_set_id AS case_set_id, g.case_mode AS case_mode, u.enabled AS user_enabled, g.enabled AS group_enabled, g.restricted_ip_address_access FROM VP_OFP.User u, VP_OFP.UserGroup g WHERE username='" + username + "' AND password='" + password + "' AND u.UserGroup_user_group_id = g.user_group_id";
					MySqlCommand command = new MySqlCommand(query, connection);
			        MySqlDataReader reader = command.ExecuteReader();
		            reader.Read();
		                
		            if (reader.HasRows)
		            {
						User.Id = (int)reader["user_id"];
		            	User.Name = reader["user_name"].ToString();
		            	User.UserName = username;
						User.CaseSetID = (int)reader["case_set_id"];
						User.CaseMode = reader["case_mode"].ToString();;
		            	bool group_enabled = (bool)reader["group_enabled"];
		            	bool user_enabled = (bool)reader["user_enabled"];
						
						if (!user_enabled || !group_enabled)
						{
							message = "User account not active";
							return;
						}
						
						User.RestrictedIpAddressAccess = (bool)reader["restricted_ip_address_access"];

						IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());

						if (User.RestrictedIpAddressAccess)
						{
							if (ips.Length == 0)
							{
								message = "Cannot identify localhost";
								return;
							}
						}
						
						connection.Close();
						
						connection.Open();
	                	query = "INSERT INTO Session VALUES (NULL, CURRENT_TIMESTAMP, NULL, '" + ips[0] + "', " + User.Id + ")";
						command = new MySqlCommand(query, connection);
						command.ExecuteNonQuery();				
	
						Application.LoadLevel(1);
		            }
					else
					{
						message = "Invalid username or password";
						return;
					}
				}				
	        }
	        catch (Exception ex)
	        {
				message = "No connection to server";
				message = ex.Message;
				return;
	        }
        }
		
		if (Event.current.isKey)
		{
			message = "";
		}
	}
}
